package com.example.rotateimageview;

import android.content.Context;
import android.util.AttributeSet;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;

/**
 * author  : Liushuai
 * time    : 2021/9/12 21:35
 * desc    :
 */
public class MyViewGroup extends ViewGroup {


    public MyViewGroup(Context context) {
        super(context);
    }

    public MyViewGroup(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec, heightMeasureSpec);

        int maxWith=0,totalHeight=0;
        for (int i = 0; i < getChildCount(); i++) {
            int childWith=getChildAt(i).getMeasuredWidth();
            if (maxWith < childWith) {
                maxWith=childWith;
            }
            totalHeight+=getChildAt(i).getMeasuredHeight();
        }

        int withMode = MeasureSpec.getMode(widthMeasureSpec);
        int withSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);


        if (withMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(maxWith,totalHeight);
        } else if (withMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(maxWith,heightSize);
        } else if (heightMode == MeasureSpec.AT_MOST) {
            setMeasuredDimension(withSize,totalHeight);
        }else{
            setMeasuredDimension(widthMeasureSpec,heightMeasureSpec);
        }
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        int top = 0;
        int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View view = getChildAt(i);
            int childWith = view.getMeasuredWidth();
            int childHeight = view.getMeasuredHeight();
            Log.i("---onLayout", childWith + "");
            view.layout(0, top, childWith, childHeight);
            top += childHeight;
        }
    }


}
